package dnavsim;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.log4j.Logger;

public class HelloWorld {

	public static void main(String[] args) {

		Logger log = Logger.getLogger("HelloWorld");

		log.info("Starting...");
		
		boolean seqHdrRead = false;
		InputStream in = null;
		OutputStream out = null;
		String headerLine = "";
		try {
			in = new BufferedInputStream(new FileInputStream("human_b36_female.chr1.fa"));
			out = new BufferedOutputStream(new FileOutputStream("out.fasta"));
			int bufLen = 10 * 1024;
			byte[] buf = new byte[bufLen];
			int len = 0;
			while ((len = in.read(buf, 0, bufLen)) != -1) {
				int i = 0;
				int j = 0;
				for (j=0; j<len; j++) {
					
					// Sequence sequence header lines
					if (buf[j] == '>') {
						if (seqHdrRead)
							throw new IOException("The FASTA file contains more than 1 sequence! Sorry but this is not supported yet.");
						seqHdrRead = true;
						int hdrStart = j+1;
						while (buf[j] != 0x0A) j++;
						int hdrEnd = j; 
						headerLine = new String(buf, hdrStart, hdrEnd-hdrStart);
						log.debug("Reading sequence '" + headerLine + "'...");
						j++;
						i = j;
					}
					
					if (buf[j] == 0x0A) {
						out.write(buf, i, (j-i));
						i = j+1;
					}
					
				}
				if (i < j+2) {
					out.write(buf, i, (j-i));
				}
			}

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// always close the stream
			if (in != null)
				try {
					in.close();
					out.close();
				} catch (Exception e) {
				}
		}

		log.info("Ending...");
	}

}
